package com.itheima.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.PageResult;
import com.itheima.mapper.PermissionMapper;
import com.itheima.mapper.RoleMapper;
import com.itheima.mapper.UserMapper;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.Set;

@Service(interfaceClass = UserService.class)
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private PermissionMapper permissionMapper;
    @Autowired
    private RoleMapper roleMapper;

    @Override
    public User findByUsername(String username) {
        //根据用户名查询用户基本信息
        User user = userMapper.SelectByUserName(username);
        if(null != user){
            //根据userid查询用户下面所有的角色
            Set<Role> roles = roleMapper.selectByUserId(user.getId());
            if(CollectionUtil.isNotEmpty(roles)){
                //循环用户所有角色查询角色对应所有的权限
                for (Role role : roles) {
                    Set<Permission> permissions = permissionMapper.selectByRoleId(role.getId());
                    role.setPermissions(permissions);
                }
            }
            user.setRoles(roles);
        }
        return user;
    }

    @Override
    public PageResult findPage(Integer currentPage, Integer pageSize, String queryString) {
        //1 调用分页组件
        PageHelper.startPage(currentPage,pageSize);
        //2 调用CheckItemDao
        List<User> userList = userMapper.findPage(queryString);
        //将查询到的数据给PageInfo进行包装
        PageInfo<User> pageInfo = new PageInfo<>(userList);
        //3 返回PageResult
        return new PageResult(pageInfo.getTotal(),pageInfo.getList());
    }

    @Override
    public void add(Integer[] roleIds, User user) {
        //新增用户
        userMapper.add(user);
        //新增中间表
        setUserAndRoleds(roleIds,user.getId());
    }

    @Override
    public void edit(Integer[] roleIds, User user) {
        //将用户和角色的中间表数据删除
        userMapper.deleteAssociation(user.getId());

        //重新添加用户和角色的中间表数据
        //新增用户和角色的中间表数据
        setUserAndRoleds(roleIds,user.getId());

        //更新用户数据
        userMapper.edit(user);
    }

    @Override
    public void deleteById(Integer id) {
        //删除中间表
        userMapper.deleteAssociation(id);
        userMapper.deleteById(id);
    }


    private void setUserAndRoleds(Integer[] roleIds, Integer id) {
        if (roleIds!=null &&roleIds.length>0){
            userMapper.setUserAndRoleds(roleIds,id);

        }
    }

}

